package com.hmall.service;

import com.alibaba.fastjson.JSON;
import com.hmall.common.myClient.ItemClient;
import com.hmall.common.pojo.Item;
import com.hmall.common.pojo.PageDTO;
import com.hmall.config.EsConstant;
import com.hmall.pojo.ItemDoc;
import com.hmall.pojo.Param;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 15198
 * @Date 2022/8/10 15:50
 * @Description:
 * @Created by
 */
@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ItemClient itemClient;





    /**
     * 分页展示
     * @param params
     * @return
     */
    @Override
    public PageDTO<ItemDoc> search(Param params) {
        try {
            SearchRequest request = new SearchRequest(EsConstant.INDEX);
            //设置分页参数
            Integer page = params.getPage();
            Integer size = params.getSize();
            //添加分页条件，抽成方法
            boolQueryGetList(params,request);
            //分页展示
            request.source().from((page - 1) * size).size(size);
            //排序
           if ("sold".equals(params.getSortBy())){
               request.source().sort(params.getSortBy(), SortOrder.DESC);
           }
           if ("price".equals(params.getSortBy())){
               request.source().sort(params.getSortBy(), SortOrder.DESC);
           }
           //设置高亮
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("all");
            highlightBuilder.requireFieldMatch(false);
            request.source().highlighter(highlightBuilder);


            //发送请求，获取结果
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 4.解析结果
            SearchHits searchHits = response.getHits();
            long total = searchHits.getTotalHits().value;

            ArrayList<ItemDoc> itemDocs = new ArrayList<>();
            for (SearchHit hit : response.getHits().getHits()) {
                String sourceAsString = hit.getSourceAsString();
                ItemDoc itemDoc = JSON.parseObject(sourceAsString, ItemDoc.class);
                //解析高亮
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if (highlightFields!=null && highlightFields.size()>0){
                    HighlightField highlightFieldName = highlightFields.get("all");
                    String name = highlightFieldName.getFragments()[0].toString();
                    itemDoc.setName(name);
                }
                //价格需要  *  100
                //itemDoc.setPrice(itemDoc.getPrice()*100);
                itemDocs.add(itemDoc);
            }
            return new PageDTO<>(total, itemDocs);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new PageDTO<>();
    }


    //搜索补全
    @Override
    public List<String> suggestion(String key) {

        //请求
        SearchRequest request = new SearchRequest(EsConstant.INDEX);

        try {
            //设置请求条件
            request.source().suggest(new SuggestBuilder()
                    .addSuggestion("suggestions", SuggestBuilders.completionSuggestion("suggestion")
                            .prefix(key)
                            .skipDuplicates(true)
                            .size(10)
                    )
            );
            //解析响应结果
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            Suggest suggest = response.getSuggest();
            CompletionSuggestion suggestion = suggest.getSuggestion("suggestions");
            List<CompletionSuggestion.Entry.Option> options = suggestion.getOptions();
            List<String> list = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                list.add(text);
            }
            return list;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }

    //聚合过滤
    @Override
    public Map<String, List<String>> filter(Param param) {

        try {
            SearchRequest request = new SearchRequest(EsConstant.INDEX);
            boolQueryGetList(param,request);
            //进行聚合查询
            aggs(request, "brandAgg", "brand");
            aggs(request, "categoryAgg", "category");
            aggs(request, "priceAgg", "price");

            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            HashMap<String, List<String>> hashMap = new HashMap<>();
            List<String> brandAgg = responseGetMapList(response, "brandAgg");
            hashMap.put("brand", brandAgg);
            List<String> categoryAgg = responseGetMapList(response, "categoryAgg");
            hashMap.put("category", categoryAgg);


            return hashMap;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new HashMap<>();
    }



    private List<String> responseGetMapList(SearchResponse response, String aggName) {
        List<String> getAggsName = new ArrayList<>();
        Terms agg = response.getAggregations().get(aggName);
        for (Terms.Bucket bucket : agg.getBuckets()) {
            String keyAsString = bucket.getKeyAsString();
            getAggsName.add(keyAsString);
        }
        return getAggsName;
    }


    private void aggs(SearchRequest request, String aggName, String aggFild) {
        request.source()
                .size(0)
                .aggregation(AggregationBuilders.terms(aggName)
                .field(aggFild)
                .size(20)
        );
    }


    //添加搜索条件方法
    private void boolQueryGetList(Param params, SearchRequest request) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (params.getKey() != null && !"".equals(params.getKey())) {
            boolQuery.must(QueryBuilders.matchQuery("all", params.getKey()));
        } else {
            boolQuery.must(QueryBuilders.matchAllQuery());
        }
        if (params.getBrand() != null && !"".equals(params.getBrand())) {
            boolQuery.must(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        if (params.getCategory() != null && !"".equals(params.getCategory())) {
            boolQuery.must(QueryBuilders.termQuery("category", params.getCategory()));
        }
        if (params.getMinPrice() != null && params.getMaxPrice() != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price").lte(params.getMaxPrice()).gte(params.getMinPrice()));
        }
        request.source().query(boolQuery);
    }


    /**
     * 数据同步,添加
     */

    @Override
    public void addByIdAndStatus(Long id){
        try {
            Item byId = itemClient.getById(id);
            ItemDoc itemDoc = new ItemDoc(byId);
            IndexRequest request = new IndexRequest(EsConstant.INDEX)
                    .id(itemDoc.getId().toString());
            request.source(JSON.toJSONString(itemDoc), XContentType.JSON);
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 数据同步，下架就删除
     * @param id
     */
    @Override
    public void deleteByIdAndStatus(Long id) {
        try {
            DeleteRequest request = new DeleteRequest(EsConstant.INDEX).id(id.toString());
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
